﻿<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">

	<head>
		<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
		<title>Dependency Injection - 依赖注入</title>
		<link type="text/css" rel="stylesheet" href="bootstrap.min.css" />
	</head>

	<body>

		<div class="document-contents">
			<h3 id="DocWhatIsDI">What is Dependency Injection - 什么是依赖注入</h3>
			<p>If you already know Dependency Injection concept, Constructor and Property 
Injection patterns, you can skip to the <a href="#DocAbpInfrastructure">next section</a>.</p>
			<p class="translation">
				如果你已经明白依赖注入的概念，构造函数和属性注入模式，你可以跳到下一节。
			</p>
			<p>Wikipedia says: "<em>Dependency injection is a software design pattern in which one or more dependencies (or services) are injected, or passed by reference, 
into a dependent object (or client) and are made part of the client's state. The pattern separates the creation of a client's dependencies from its own behavior,
which allows program designs to be loosely coupled and to follow the dependency inversion and single responsibility principles. It directly contrasts the
service locator pattern, which allows clients to know about the system they use to find dependencies.</em>".</p>
			<p>It's very hard to manage dependencies and develop a modular and well 
structured application without using dependency injection techniques.</p>
			<p class="translation">
				在不使用依赖注入技术的情况下，很难进行依赖管理、开发一个模块化且结构良好的应用程序。
			</p>
			<h4 id="DocProblems">Problems of Traditional Way - 传统方法的问题</h4>
			<p>In an application, classes depend on each other. Assume that we have an
				<a href="/Pages/Documents/Application-Services">application service</a> that 
uses a <a href="/Pages/Documents/Entities">repository</a> to insert
				<a href="/Pages/Documents/Entities">entities</a> to database. In this 
situation, the application service class is dependent to the repository class. 
See the example:</p>
			<p class="translation">
				在一个应用程序中，类相互依赖。假设我们有一个<a href="/Application-Services">应用程序服务</a>，
				使用<a href="/Repositories">仓库</a>来插入<a href="/Entities">实体</a>到数据库。
				在这种情况下，应用程序服务类依赖于仓库类。看以下例子：
			</p>
			<pre lang="cs">public class PersonAppService
{
    private IPersonRepository _personRepository;

    public PersonAppService()
    {
        _personRepository = new PersonRepository();            
    }

    public void CreatePerson(string name, int age)
    {
        var person = new Person { Name = name, Age = age };
        _personRepository.Insert(person);
    }
}
			</pre>
			<p>
				<strong>PersonAppService</strong> uses <strong>PersonRepository</strong> to 
insert a <strong>Person</strong> to the database. Problems of this code:</p>
			<p class="translation">
				<strong>PersonAppService</strong> 使用 <strong>PersonRepository</strong> 来插入一个 <strong>Person</strong> 到数据库。
				这些代码有如下问题：
			</p>
			<ul>
				<li>PersonAppService uses <strong>IPersonRepository</strong> reference in
					<strong>CreatePerson</strong> method, so this method depends on 
	IPersonRepository, instead of PersonRepository concrete class. But the 
	PersonAppService still depends on PersonRepository in it's constructor. 
	Components should depend on interfaces rather than implementation. This is 
	known as Dependency Inversion principle. </li>
				<p class="translation">
					PersonAppService 在 <strong>CreatePerson</strong> 方法中使用了 <strong>IPersonRepository</strong> 引用，
					因此这个方法依赖于 IPersonRepository 而不是 PersonRepository 具体类。
					但是，PersonAppService 在它的构造函数中仍然依赖于 PersonRepository。
					组件应该依赖于接口而不是实现。这就是所谓的依赖倒置原则。
				</p>
				<li>If the PersonAppService creates the PersonRepository itself, it become 
	dependent to a specific implementation of IPersonRepository interface and 
	can not work with another implementation. Thus, separating interface from 
	implementation becomes meaningless. Hard-dependencies makes code base 
	tightly coupled and low re-usable.</li>
				<p class="translation">
					如果 PersonAppService 自身创建了 PersonRepository，它变成了依赖于 IPersonRepository 的一个特定实现而不能与其它实现一起工作。
					因此，从实现中分离接口变得毫无意义。硬依赖使用代码紧密耦合和较低的复用。
				</p>
				<li>We may need to change creation of PersonRepository in the future. Say, 
	we may want to make it singleton (single shared instance rather than 
	creating an object for each usage). Or we may want to create more than one 
	class those implement IPersonRepository and we want to create one of them 
	conditionally. In this situation, we should change all classes that depends 
	on IPersonRepository.</li>
				<p class="translation">
					我们也许需要在未来改变 PersonRepository 的创建。
					比如，我们也许想以单例方式创建它（单一共享实例而不是每次使用时创建一个对象）。
					或者我们也许想创建 IPersonRepository 的多个实现类，并根据条件创建它们中的一个。
					在这种情况下，我们应该修改所有依赖于 IPersonRepository 的类。
				</p>
				<li>With such a dependency, it's very hard (or impossible) to unit test the 
	PersonAppService.</li>
				<p class="translation">
					有了像这样的依赖，很难（或不可能）对 PersonAppService 进行单元测试。
				</p>
			</ul>
			<p>To overcome some of these problems, factory pattern can be used. Thus, creation 
of repository class is abstracted. See the code below:</p>
			<p class="translation">
				为了克服这些问题，可以使用工厂模式。因此，创建的仓库类是抽象的。看下面的代码：
			</p>
			<pre lang="cs">public class PersonAppService
{
    private IPersonRepository _personRepository;

    public PersonAppService()
    {
        _personRepository = PersonRepositoryFactory.Create();            
    }

    public void CreatePerson(string name, int age)
    {
        var person = new Person { Name = name, Age = age };
        _personRepository.Insert(person);
    }
}
			</pre>

			<p>PersonRepositoryFactory is a static class that creates and returns an 
IPersonRepository. This is known as <strong>Service Locator</strong> pattern. Creation problems are solved since PersonAppService does not 
know how to create an implementation of IPersonRepository and it's independent 
from PersonRepository implementation. But,still there are some problems:</p>
			<p class="translation">
				PersonRepositoryFactory 是一个静态类，它创建并返回一个 IPersonRepository。这就是所谓的服务定位器模式。
				上述的创建问题得到了解决，因为 PersonAppService 不用知道 IPersonRepository 的实现如何创建，并且它是独立于 PersonRepository 的实现。
				但是，仍然存在一些问题：
			</p>
			<ul>
				<li>In this time, PersonAppService depends on PersonRepositoryFactory. This 
	is more acceptable but still there is a hard-dependency.</li>
				<p class="translation">
					此时，PersonAppService 依赖于 PersonRepositoryFactory。这点更容易接受但仍然存在一个硬依赖。
				</p>
				<li>It's tedious to write a factory class/method for each repository or for 
	each dependency.</li>
				<p class="translation">
					为每个仓库或依赖写一个工厂类/方法是单调乏味的。
				</p>
				<li>It's not well testable again, since it's hard to make PersonAppService 
	to use some mock implementation of IPersonRepository.</li>
				<p class="translation">
					测试性依然不好，因为很难使 PersonAppService 使用伪装来实现 IPersonRepository。
				</p>
			</ul>
			<h4 id="DocSolution">Solution - 解决方案</h4>
			<p>There are some best practices (patterns) to depend on other classes.</p>
			<p class="translation">有一些最佳实践（模式）用于类依赖。</p>
			<h5 id="DocConstructorInjection">Constructor Injection Pattern - 构造函数注入模式</h5>
			<p>The example above can be re-written as shown below:</p>
			<p class="translation">上述的例子可以被重写为：</p>
			<pre lang="cs">public class PersonAppService
{
    private IPersonRepository _personRepository;

    public PersonAppService(IPersonRepository personRepository)
    {
        _personRepository = personRepository;
    }

    public void CreatePerson(string name, int age)
    {
        var person = new Person { Name = name, Age = age };
        _personRepository.Insert(person);
    }
}
			</pre>

			<p>This is known as <strong>constructor injection</strong>. Now, 
PersonAppService does not know which classes implement IPersonRepository and how 
to create it. Who needs to use PersonAppService, first creates an 
IPersonRepository and pass it to constructor of PersonAppService as shown below:</p>
			<p class="translation">
				这被称为<strong>构造函数注入</strong>。现在，PersonAppService 不用知道是哪个类实现了 IPersonRepository 及其如何创建了它。
				谁需要使用 PersonAppService，首先创建一个 IPersonRepository，并传递它给 PersonAppService 的构造函数，如下所示：
			</p>
			<pre lang="cs">var repository = new PersonRepository();
var personService = new PersonAppService(repository);
personService.CreatePerson("Yunus Emre", 19);</pre>
			<p>Constructor Injection is a perfect way of making a class independent to 
creation of dependent objects. But, there are some problems with the code above:</p>
			<p class="translation">
				构造函数注入是让一个类独立于依赖对象的创建的完善方法。但是，上述代码有一些问题：
			</p>
			<ul>
				<li>Creating a PersonAppService become harder. Think that it has 4 
	dependency, we must create these 4 dependent object and pass them into the 
	constructor of the PersonAppService.</li>
				<p class="translation">
					创建一个 PersonAppService 变得困难。
					想像一下如果它拥有 4 个依赖，我们必须创建这 4 个依赖对象，并将它们传递到 PersonAppService 的构造函数。
				</p>
				<li>Dependent classes may have other dependencies (Here, PersonRepository 
	may has dependencies). So, we must create all dependencies of 
	PersonAppService, all dependencies of dependencies and so on.. In that way, 
	we may not even create a single object since dependency graph is too 
	complex.</li>
				<p class="translation">
					依赖类也许拥有其它依赖（在这里，PersonRepository 也许拥有依赖）。
					所以，我们必须创建 PersonAppService 的所有依赖，及其依赖的依赖。
					那么，依赖关系使得我们创建一个对象变得过于复杂了。
				</p>
			</ul>
			<p>Fortunately, there are <a href="#DocDIFrameworks">Dependency Injection 
frameworks</a> automates to manage dependencies.</p>
			<p class="translation">
				幸运的是，有<a href="#DocDIFrameworks">依赖注入框架</a>自动来管理依赖。
			</p>
			<h5 id="DocPropertyInjection">Property Injection pattern - 属性注入模式</h5>
			<p>Constructor injection pattern is a perfect way of providing dependencies of a 
class. In this way, you can not create an instance of the class without 
supplying dependencies. It's also a strong way of explicitly declaring what's 
the requirements of the class to properly work.</p>
			<p class="translation">
				构造函数注入模式是为一个类提供依赖关系的完美方法。在这种方法中，当没有提供依赖时你不可以创建类的实例。
				它还是用于显式声明类需要什么样的依赖才能正确工作的强大方法。
			</p>
			<p>But, in some situations, the class depends on another class but also can work 
without it. This is usually true for cross-cutting concerns such as logging. A 
class can work without logging, but it can write logs if you supply a logger. In 
this case, you can define dependencies as public properties rather than getting 
them in constructor. Think that we want to write logs in PersonAppService. We 
can re-write the class as like below:</p>
			<p class="translation">
				但是，在某些情况下，类依赖于其一个类，但在不使用它的情况下也能工作。这通常适用于横切关注点，像日志记录。
				一个类可以在没有日志记录的情况下工作，但如果提供了一个记录器它可以写日志。
				在这种情况下，你可以定义依赖作为公共属性而不是在构造函数中得到它们。
				想像一下我们想在 PersonAppService 中书写日志。我们可以像下面一样重写类：
			</p>
			<pre lang="cs">public class PersonAppService
{
    public ILogger Logger { get; set; }

    private IPersonRepository _personRepository;

    public PersonAppService(IPersonRepository personRepository)
    {
        _personRepository = personRepository;
        Logger = NullLogger.Instance;
    }

    public void CreatePerson(string name, int age)
    {
        Logger.Debug("Inserting a new person to database with name = " + name);
        var person = new Person { Name = name, Age = age };
        _personRepository.Insert(person);
        Logger.Debug("Successfully inserted!");
    }
}</pre>
			<p>NullLogger.Instance is a singleton object that implements ILogger but 
actually does nothing (does not write logs. It implements ILogger with empty 
method bodies). So, now, PersonAppService can write logs if you set Logger after 
creating the PersonAppService object like below:</p>
			<p class="translation">
				NullLogger.Instance 是实现了 ILogger 的单例对象，但它实际上什么事都不干（没有写日志。它使用空方法体实现了 ILogger）。
				所以，现在，在创建 PersonAppService 对象后如果你设置了 Logger，PersonAppService 就可以写日志。
			</p>
			<pre lang="cs">var personService = new PersonAppService(new PersonRepository());
personService.Logger = new Log4NetLogger();
personService.CreatePerson("Yunus Emre", 19);</pre>
			<p>Assume that Log4NetLogger implements ILogger and write logs using Log4Net 
library. Thus, PersonAppService can actually write logs. If we do not set 
Logger, it does not write logs. So, we can say the ILogger is an <strong>
optional dependency </strong>of PersonAppService.</p>
			<p class="translation">
				假设 Log4NetLogger 实现了 ILogger，使用 Log4Net 库来写日志。因此，PersonAppService 可以实际写日志。
				如果我们没有设置 Logger，它就不会写日志。因此，我们可以说 ILogger 是 PersonAppService 的<strong>可选依赖</strong>。
			</p>

			<p>Almost all of Dependency Injection frameworks support Property Injection 
pattern.</p>
			<p class="translation">几乎所有依赖注入框架都支持属性注入模式。</p>
			<h5 id="DocDIFrameworks">Dependency Injection frameworks - 依赖注入框架</h5>
			<p>There are many dependency injection framework that automates resolving 
dependencies. They can create objects with all dependencies (and dependencies of 
dependencies recursively). So, you just write your class with constructor &amp; 
property injection patterns, DI framework handles the rest! In a good 
application, your classes are independent even from DI framework. There will be 
a few lines of code or classes that explicitly interact with DI framework in 
your whole application.</p>
			<p class="translation">
				有诸多依赖注入框架可以自动解析依赖关系。它们可以创建带有所有依赖关系的对象（递归的依赖关系）。
				因此，你仅需要使用构造函数 &amp; 属性注入模式来编写类，DI 框架将处理剩余部分！
				在一个良好的应用程序中，你的类也是独立于 DI 框架的。整个应用程序中将只有几行代码或类显工的与 DI 框架交互。
			</p>
			<p>ASP.NET Boilerplate uses <a href="http://docs.castleproject.org/Default.aspx?Page=MainPage">Castle 
Windsor</a>  framework for Dependency Injection. It's one of the most mature DI 
frameworks. There are many other frameworks like Unity, Ninject, StructureMap, 
Autofac and so on.</p>
			<p class="translation">
				ASP.NET Boilerplate 使用 <a href="http://docs.castleproject.org/Default.aspx?Page=MainPage">Castle Windsor</a> 框架用于依赖注入。
				它是最成熟的 DI 框架之一。还有很多其它的框架，像 Unity, Ninject, StructureMap, Autofac 等。
			</p>
			<p>In a dependency injection framework, you first register your 
interfaces/classes to the dependency injection framework, then you can resolve 
(create) an object. In Castle Windsor, 
it's something like that:</p>
			<p class="translation">
				在一个依赖注入框架中，你首先注册你的接口/类到依赖注入框架，然后你可以解析（创建）一个对象。
				在 Castle Windsor 中，它是这样的：
			</p>
			<pre>var container = new WindsorContainer();

container.Register(
        Component.For&lt;IPersonRepository&gt;().ImplementedBy&lt;PersonRepository&gt;().LifestyleTransient(),
        Component.For&lt;IPersonAppService&gt;().ImplementedBy&lt;PersonAppService&gt;().LifestyleTransient()
    );

var personService = container.Resolve&lt;IPersonAppService&gt;();
personService.CreatePerson(&quot;Yunus Emre&quot;, 19);</pre>
			<p>We first created the <strong>WindsorContainer</strong>. then <strong>
registered </strong>PersonRepository and PersonAppService with their interfaces. 
Then we asked to container to create an IPersonAppService. It created 
PersonAppService with dependencies and returned back. Maybe it's not so clear of 
advantage of using a DI framework in this simple example, but think you will 
have many classes and dependencies in a real enterprise application. Surely, 
registering dependencies will be somewhere else from creation and using objects 
and made only one time in an application startup.</p>
			<p class="translation">
				我们首先创建了 <strong>WindsorContainer</strong>。然后使用 PersonRepository 和 PersonAppService 的接口<strong>注册</strong>了它们。
				然后我们告诉容器创建一个 IPersonAppService。它使用依赖关系创建 PersonAppService 并返回。
				在这个简单的示例中，使用 DI 框架的优势并不明显，但你想你一下在真实的企业应用程序中你将拥有许多类及其依赖。
				当然，注册依赖关系与创建并使用对象不在同一位置，并且仅在应用程序启动中创建一次。
			</p>
			<p>Notice that we also declared <strong>life cycle </strong>of objects as
				<strong>transient</strong>. That means whenever we resolves an object of these 
types, a new instance will be created. There are many different life cycles 
(like <strong>singletion</strong>).</p>
			<p class="translation">
				注意，我们还声明对象的生命周期为瞬时。这意味着每当多们解析这些类型的一个对象时，一个新实例将被创建。
				有许多不同的生命周期（像单例）。
			</p>
			<h3 id="DocAbpInfrastructure">ASP.NET Boilerplate Dependency Injection 
			Infrastructure - ASP.NET Boilerplate 依赖注入基础设施</h3>
			<p>ASP.NET Boilerplate almost makes invisible of using the dependency injection 
framework when you write your application by following best practices and some 
conventions.</p>
            <p class="translation">
				当你遵循最佳实践和一些约定来编写你的应用程序时，ASP.NET Boilerplate 几乎让使用的依赖注入框架变得透明。
			</p>
			<h4 id="DocRegisterDependencies">Registering Dependencies - 注册依赖</h4>
			<p>There are different ways of registering your classes to Dependency Injection 
system in ASP.NET Boilerplate. Most of time, conventional registration will be 
sufficient.</p>
			<p class="translation">
				在 ASP.NET Boilerplat 中有不同的方法注册你的类到依赖注入系统。大多数时候，约定注册就足够用。
			</p>
			<h5 id="DocConventionalRegister">Conventional Registrations - 约定注册</h5>

			<p>ASP.NET Boilerplate automatically registers all
				<a href="/Pages/Documents/Repositories">Repositories</a>, 
				<a href="/Pages/Documents/Domain-Services">Domain Services</a>,
				<a href="/Pages/Documents/Application-Services">Application Services</a>, MVC 
Controllers and Web API Controllers 
by 
convention. For example, you may have a IPersonAppService interface and a PersonAppService 
class that implements it:</p>
			<p class="translation">
				ASP.NET Boilerplate 通过约定自动注册所有的<a href="/Repositories">仓库</a>，<a href="/Domain-Services">领域服务</a>，<a href="/Application-Services">应用程序服务</a>，MVC 控制器及 Web API 控制器。
				例如，你拥有一个 IPersonAppService 接口及实现它的 PersonAppService 类：
			</p>
			<pre>public interface IPersonAppService : IApplicationService
{
    //...
}

public class PersonAppService : IPersonAppService
{
    //...
}</pre>
			<p>ASP.NET Boilerplate automatically registers it since it implements <strong>
IApplicationService </strong>interface (It's just an empty interface). It's 
registered as <strong>transient </strong>(created instance per usage). When you 
inject (using constructor injection) IPersonAppService interface to a class, a 
PersonAppService object is created and passed into constructor automatically. </p>
			<p class="translation">
				ASP.NET Boilerplate 自动注册了它，因为它实现了 <strong>IApplicationService</strong> 接口（它只是一个空接口）。
				它是以<strong>瞬时</strong>方式注册的（每次使用创建实例）。
				当你注入（使用构造函数注入）IPersonAppService 接口到一个类时，PersonAppService 对象将被自动创建并传递到构造函数中。
			</p>
			<p>
				<strong>Naming conventions </strong>are very important here. For example you 
can change name of PersonAppService to MyPersonAppService or another name which 
contains 'PersonAppService' postfix since the IPersonAppService has this 
postfix. But you can not name your service as PeopleService. If you do it, it's 
not registered for IPersonAppService automatically (It's registered to DI 
framework but with self-registration, not with interface), so, you should manually 
register it if you want.</p>
			<p class="translation">
				<strong>命名约定</strong>在这里非常重要。例如你可以修改 PersonAppService 为 MyPersonAppService 或包含 ‘PersonAppService’后缀的其它名称，因为 IPersonAppService 拥有这个后缀。
				但你不可以命名你的服务为 PeopleService。如果你这样做了，它将不会为 IPersonAppService 自动注册（它注册到 DI 框架的是自注册而没有使用接口），所以如果你想拥有它你应该手动注册它。
			</p>
			<p>ASP.NET Boilerplate can register assemblies by convention. You 
			can tell 
ASP.NET Boilerplate to register your assembly by convention. It's pretty 
easy:</p>
			<p class="translation">
				ASP.NET Boilerplate 可以通过约定来注册程序集。你可以告诉 ASP.NET Boilerplate 通过约定注册你的程序集。这很容易：
			</p>
			<pre lang="cs">IocManager.RegisterAssemblyByConvention(Assembly.GetExecutingAssembly());</pre>
			<p>Assembly.GetExecutingAssembly() gets a reference to the assembly which 
contains this code. You can pass other assemblies to 
RegisterAssemblyByConvention method. This is generally done when your module is 
being initialized. See ASP.NET Boilerplate's
				<a href="/Pages/Documents/Module-System">module system</a> for more.</p>
			<p class="translation">
				Assembly.GetExecutingAssembly() 得到了一个包含这些代码程序集的引用。
				你可以传递其它程序集到 RegisterAssemblyByConvention 方法。
				这通常在你的模块初始化后完成。更多信息参阅 ASP.NET Boilerplate 的<a href="/Module-System">模块系统</a>。
			</p>
			<p>You can write your own conventional registration class by implementing
				<strong>IConventionalRegisterer</strong> interface and calling <strong>IocManager.AddConventionalRegisterer</strong> 
method with your class. You should add it in pre-initialize method of your 
module.</p>
			<p class="translation">
				你可以通过在你的类中实现 <strong>IConventionalRegisterer</strong> 接口及调用 <strong>IocManager.AddConventionalRegisterer</strong> 方法来编写你自己的约定登记器。
				你应该在模块的预初始化方法中添加它。
			</p>
			<h5 id="DocHelperInterfaces">Helper Interfaces -- 辅助接口</h5>
			<p>You may want to register a specific class that does not fit to conventional 
registration rules. ASP.NET Boilerplate provides <strong>ITransientDependency</strong> and 
				<strong>ISingletonDependency</strong> interfaces as a shortcut. For example:</p>
			<p class="translation">
				你可能想注册一个不符合约定登记规则的特定类。
				ASP.NET Boilerplate 提供了 ITransientDependency 和 ISingletonDependency 接口作为快捷方法。
				例如：
			</p>
			<pre lang="cs">public interface IPersonManager
{
    //...
}

public class MyPersonManager : IPersonManager, ISingletonDependency
{
    //...
}</pre>
			<p>In that way, you can easily register MyPersonManager. When need 
to inject a IPersonManager, MyPersonManager class is used. Notice that dependency is 
declared as <strong>Singleton</strong>. Thus, a single instance of 
MyPersonManager is created and same object is passed to all needed classes. It's 
just created in first usage, then same instance is used in whole life of the 
application.</p>
			<p class="translation">
				在这种方式中，你可以更容易的注册 MyPersonManager。当需要去注入 IPersonManager 时，MyPersonManager 类将被使用。
				注意依赖被作为单例声明。因此，创建的 MyPersonManager 单一实例被传递传递给所有需要的类。
				它只在第一次使用时被创建，然后在应用程序的整个生命周期中使用的是同一实例。
			</p>

			<h5 id="DocCustomRegistration">Custom/Direct Registration - 自定义/直接注册</h5>
			<p>If conventional registrations are not sufficient for your situation, you 
can either use <strong>IocManager</strong> or <strong>Castle Windsor</strong> to 
			register your classes and dependencies.</p>
			<p class="translation">
				如果约定注册不能满足你的情况，你可以使用 <strong>IocManager</strong> 或 <strong>Castle Windsor</strong> 来注册你的类及其依赖关系。
			</p>
			<h6>Using IocManager - 使用 IocManager</h6>
			<p>You can use <strong>IocManager</strong> to register dependencies (generally in 
			PreInitialize of your <a href="/Module-System.html">module definition</a> 
			class):</p>
			<p class="translation">
				你可以使用 <strong>IocManager</strong> 来注册依赖关系（通常在你的<a href="/Module-System.html">模块</a>定义的 PreInitialize 中）：
			</p>
			<pre lang="cs">IocManager.Register&lt;IMyService, MyService&gt;(DependencyLifeStyle.Transient);</pre>
			<p>Using Castle Windsor API - 使用 Castle Windsor API</p>
			<p>You can use <strong>IIocManager.IocContainer</strong> 
			property to access to the Castle Windsor Container and register 
			dependencies. Example:</p>
			<p class="translation">
				你可以使用 <strong>IIocManager.IocContainer</strong> 属性来访问 Castle Windsor 容器以及注册依赖关系。例如：
			</p>
			<pre lang="cs">IocManager.IocContainer.Register(Classes.FromThisAssembly().BasedOn&lt;IMySpecialInterface&gt;().LifestylePerThread().WithServiceSelf());</pre>
			&nbsp;For more information, read
			<a href="https://github.com/castleproject/Home/blob/master/README.md">Windsor's 
documentation</a>&nbsp;
			<p class="translation">更多信息，阅读 <a href="https://github.com/castleproject/Home/blob/master/README.md">Windsor 文档</a></p>
			<h4 id="DocResolvingDependencies">Resolving - 解析</h4>
			<p>Registration informs IOC (Inversion of Control) Container (a.k.a. DI 
framework) about your classes, their dependencies and lifetimes. Somewhere in 
your application you need to create objects using IOC Container. ASP.NET 
Provides a few options for resolving dependencies.</p>
			<p class="translation">
				登录信息告诉 IOC（控制反转）容器（也称为 DI 框架）与你的类有关的信息，它们的依赖关系及生命周期。
				在你的应用程序的有些位置，你需要使用 IOC 容器创建对象。ASP.NET 为解析依赖关系提供了一些选项。
			</p>
			<h4 id="DocResolveConstAndProp">Constructor &amp; Property Injection - 构造函数 &amp; 属性注入</h4>
			<p>You can use constructor and property injection to get dependencies to your 
classes as <strong>best practice</strong>. You should do it that way wherever 
it's possible. An example:</p>
			<p class="translation">
				作为最佳实践，你可以使用构造函数或属性注入来获取你的类的依赖关系。只要有可能你就应该这样做。例如：
			</p>
			<pre lang="cs">public class PersonAppService
{
    public ILogger Logger { get; set; }

    private IPersonRepository _personRepository;

    public PersonAppService(IPersonRepository personRepository)
    {
        _personRepository = personRepository;
        Logger = NullLogger.Instance;
    }

    public void CreatePerson(string name, int age)
    {
        Logger.Debug("Inserting a new person to database with name = " + name);
        var person = new Person { Name = name, Age = age };
        _personRepository.Insert(person);
        Logger.Debug("Successfully inserted!");
    }
}</pre>
			<p>IPersonRepository is injected from constructor and ILogger is injected with 
public property. In that way, your code will be unaware of dependency injection 
system at all. This is the most proper way of using DI system.</p>
			<p class="translation">
				IPersonRepository 从构造函数注入的，ILogger 是使用公共属性注入的。
				这样，你的代码将无法察觉依赖注入系统。这是使用 DI 系统最恰当的方式。
			</p>
			<h4 id="DocIocHelper">IIocResolver, IIocManager and 
			IScopedIocResolver </h4>
			<p>You may have to directly resolve your dependency instead of 
constructor &amp; property injection. This should be avoided when possible, but it 
may be impossible. ASP.NET Boilerplate provides some services those can be injected 
and used easily. Example:</p>
			<p class="translation">
				你也许不得不直接解析你的依赖而不是使用构造函数 &amp; 属性注入。
				这种情况应该尽可能的避免。
				ASP.NET Boilerplate 提供了一些服务，它们可以更容易的被注入和使用。例如：
			</p>
			<pre lang="cs">public class MySampleClass : ITransientDependency
{
    private readonly IIocResolver _iocResolver;

    public MySampleClass(IIocResolver iocResolver)
    {
        _iocResolver = iocResolver;
    }

    public void DoIt()
    {
        //Resolving, using and releasing manually
        var personService1 = <strong>_iocResolver.Resolve&lt;PersonAppService&gt;()</strong>;
        personService1.CreatePerson(new CreatePersonInput { Name = &quot;Yunus&quot;, Surname = &quot;Emre&quot; });
        <strong>_iocResolver.Release(personService1);</strong>

        //Resolving and using in a safe way
        using (var personService2 = <strong>_iocResolver.ResolveAsDisposable&lt;PersonAppService&gt;()</strong>)
        {
            <strong>personService2.Object</strong>.CreatePerson(new CreatePersonInput { Name = &quot;Yunus&quot;, Surname = &quot;Emre&quot; });
        }
    }
}</pre>
			<p>MySampleClass in an example class in an application. It constructor-injected
				<strong>IIcResolver</strong> and used it to resolve and release objects. There 
are a few overloads of <strong>Resolve</strong> method can be used as needed.<strong> Release </strong>method is used to 
release component (object). It's <strong>critical </strong>
to call Release if you're manually resolving an object. Otherwise, your 
application may have memory leak problem. To be sure of releasing the object, 
use <strong>ResolveAsDisposable</strong> (as shown in the example above) 
wherever it's possible. It automatically calls Release at the end of the using block.</p>
			<p class="translation">
				MySampleClass 是一个应用程序中的示例类。它通过构造函数注入了 <strong>IIcResolver</strong>，使用它来解析及释放对象。
				有一些 <strong>Resolve</strong> 方法的重载可以被需要时使用。<strong>Release</strong> 方法被用来释放组件（对象）。
				如果你手动解析一个对象，调用 Release 是非常<strong>重要的</strong>。否则，你的应用程序可能存在内存泄漏的问题。
				为了确保对象的释放，尽可能使用 <strong>ResolveAsDisposable</strong>。它在 using 代码块的结尾自动调用 Release。
			</p>
			<p>IIocResolver (and IIocManager) have also <strong>CreateScope</strong> extension 
			method (defined in Abp.Dependency namespace) to safely release all 
			resolved 
			dependencies. Example:</p>
			<p class="translation">
				IIocResolver（及 IIocManager）还拥有 <strong>CreateScope</strong> 扩展方法（定义在 Abp.Dependency 命名空间），它用来安全释放所有解析的依赖关系。
			</p>
			<pre lang="xml">using (var scope = <strong>_iocResolver.CreateScope()</strong>)
{
    var simpleObj1 = scope.Resolve&lt;SimpleService1&gt;();
    var simpleObj2 = scope.Resolve&lt;SimpleService2&gt;();
    //...
}</pre>
			<p>In the end of using block, all resolved dependencies 
			automatically removed. A scope is also injectable using <strong>
			IScopedIocResolver</strong>. You can inject this interface and 
			resolve dependencies. When your class is released, all resolved 
			dependencies will be released. But use it carefully; For example, if 
			your class has a long life (say it&#39;s a singleton) and you are 
			resolving too many objects, then all of them will remain in the 
			memory until your class is released.</p>
			<p class="translation">
				在 using 块结束时，所有解析的依赖关系将被自动移除。一个范围也可以使用 <strong>IScopedIocResolver</strong> 注入。
				你可以注入这个接口并解析依赖关系。当你的类被释放时，它的所有依赖关系将全部被释放。但你要小心谨慎地使用它；
				例如，如果你的类拥有很长的生命周期（比如它是单例）并且解析了太多的对象，那么它们会一直停留在内存中，直到你的类被释放。
			</p>
			<p>If you want to directly reach to IOC Container (Castle Windsor) to resolve dependencies, you 
can consturctor-inject <strong>IIocManager</strong> and use <strong>IIocManager.IocContainer</strong> 
property. If you are in a static context or can not inject IIocManager, as a 
last chance, you can use singleton object <strong>IocManager.Instance</strong> 
everywhere. But, in that case your codes will not be easy to test.</p>
			<p class="translation">
				如果你想直接运用 IOC 容器（Castle Windsor）来解析依赖关系，可以通过构造函数注入 IIocManager 并使用 <strong>IIocManager.IocContainer</strong> 属性。
				如果你在静态环境中或不能注入 <strong>IIocManager</strong>，则最后一次机会是使用 <strong>IocManager.Instance</strong> 单例对象。
				但是，在这种情况下你的代码将非常不容易测试。
			</p>
			<h4>Extras - 附加</h4>
			<h5>IShouldInitialize interface - IShouldInitialize 接口</h5>
			<p>Some classes need to be initialized before first usage. IShouldInitialize has 
an Initialize() method. If you implement it, then your Initialize() method is 
automatically called just after creating your object (before used). Surely, you 
should inject/resolve the object in order to work this feature.</p>
			<p class="translation">
				某些类需要在首先使用时被初始化。IShouldInitialize 拥有一个 Initialize() 方法。
				如果你实现了它，那么你的对象创建之后（被使用之前）你的 Initialize() 方法将被自动调用。
				当然，为了与这个特性一起工作你应该注入/解析对象。
			</p>

			<h4 id="DocMvcAndWebApiIntegration">ASP.NET MVC &amp; ASP.NET Web API integration - ASP.NET MVC &amp; ASP.NET Web API 整合</h4>
			<p>We must call dependency injection system to resolve the root object 
in dependency graph. In an <strong>ASP.NET MVC </strong>application, it's 
generally a <strong>Controller </strong>class. We can use contructor injection and property injection
patterns also in controllers. When a request come to our application, the 
controller is created using IOC container and all dependencies are resolved 
recursively. So, who does that? It's done automatically by ASP.NET Boilerplate 
by extending ASP.NET MVC's default controller factory. As similar, it's true for 
ASP.NET Web API also. You don't care about creating and disposing objects.</p>
			<p class="translation">
				我们必须调用依赖注入系统来解析依赖关系图中的根对象。在 <strong>ASP.NET MVC</strong> 应用程序中，它通常是一个 <strong>Controller</strong> 类。
				我们同样可以在控制器中使用构造函数注入和属性注入模式。
				当一个请求到达我们的应用程序时，控制器将被使用 IOC 容器创建并且递归解析所有的依赖关系。
				那么，这些是谁做的？它是由 ASP.NET Boilerplate 扩展的 ASP.NET MVC 默认控制器工厂自动完成的。
				与此类似，ASP.NET Web API 同样如此。你不用关注对象的创建及释放。
			</p>

			<h4>ASP.NET Core Integration - ASP.NET Core 整合</h4>
			<p>ASP.NET Core has already a built-in dependency injection system 
			with
			<a href="https://www.nuget.org/packages/Microsoft.Extensions.DependencyInjection" target="_blank">
			Microsoft.Extensions.DependencyInjection</a> package. ABP uses
			<a href="https://www.nuget.org/packages/Castle.Windsor.MsDependencyInjection" target="_blank">
			Castle.Windsor.MsDependencyInjection</a> package to integrate it's 
			dependency injection system with ASP.NET Core's. So, you don't have 
			to think about it.</p>
			<p class="translation">
				ASP.NET Core 已经内置了依赖注入系统，使用 <a href="https://www.nuget.org/packages/Microsoft.Extensions.DependencyInjection" target="_blank">Microsoft.Extensions.DependencyInjection</a> 包。
				ABP 使用 <a href="https://www.nuget.org/packages/Castle.Windsor.MsDependencyInjection" target="_blank">Castle.Windsor.MsDependencyInjection</a> 包来整合依赖注入系统到 ASP.NET Core。
				因此，你不需要考虑这些问题。
			</p>
			<h4>Last notes - 最后的说明</h4>
			<p>ASP.NET Boilerplate simplifies and automates using dependency injection as 
long as you follow the rules and use the structures above. Most of times you 
will not need more. But if you need, you can directly use all power of Castle 
Windsor to perform any task (like custom registrations, injection hooks, 
interceptors and so on).</p>
			<p class="translation">
				只要你遵循规则及使用上述的结构，ASP.NET Boilerplate 将简化并自动使用依赖注入。
				大多数时候你不需要更多。但是如果你需要，你可以直接使用 Castle Windsor 所有能力来执行任何任务（如自定义注册，注入钩子，拦截器等等）。
			</p>
		</div>
	</body>

</html>
